package cn.jingyuan.bee.fastjson;

import cn.jingyuan.bee.enums.EnumInteger;
import cn.jingyuan.bee.enums.EnumString;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;

import java.lang.reflect.Type;


public class BeeParserConfig extends ParserConfig {

    public static final ParserConfig global = new BeeParserConfig();

    public static ParserConfig getGlobal() {
        return global;
    }

    @Override
    public ObjectDeserializer getDeserializer(Class<?> clazz, Type type) {
        ObjectDeserializer deserializer;
        if (clazz.isEnum()) {
            JSONType jsonType = clazz.getAnnotation(JSONType.class);

            if (null != jsonType) {
                Class<?> aClass = jsonType.deserializer();
                try {
                    deserializer = (ObjectDeserializer) aClass.newInstance();
                    this.putDeserializer(type, deserializer);
                    return deserializer;
                } catch (Throwable error) {
                    // skip
                }
            } else {
                if (EnumString.class.isAssignableFrom(clazz)) {
                    deserializer = EnumStringSerializer.instance;
                    return deserializer;
                }

                if (EnumInteger.class.isAssignableFrom(clazz)) {
                    deserializer = EnumIntegerSerializer.instance;
                    return deserializer;
                }
            }
        }
        return super.getDeserializer(clazz, type);
    }

}
